/*
 * Copyright (C) 2008 GeoScheduler team, as stated on <http://www.geoscheduler.org/authors>.
 * 
 * This file is part of GeoScheduler.
 * 
 * GeoScheduler is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * GeoScheduler is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with GeoScheduler. If not, see <http://www.gnu.org/licenses/>.
 */
package org.geoscheduler.android.activities;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;

import org.geoscheduler.android.R;
import org.geoscheduler.android.tools.DBHelper;
import org.geoscheduler.android.tools.DateTimeHelper;
import org.geoscheduler.android.tools.FormatHelper;
import org.geoscheduler.model.Event;
import org.geoscheduler.model.Location;
import org.geoscheduler.model.Tag;
import org.geoscheduler.model.Event.AlertType;
import org.geoscheduler.model.Event.EventType;
import org.geoscheduler.model.Event.RepeatType;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TimePicker;
import android.widget.Toast;

/**
 * EditEvent Activity of GeoScheduler client application
 * 
 * @author paja
 */
public class EditEvent extends Activity {

	/* TODO: providers should change */
	public static final String FIXED_LOCATION_PROVIDER = "gps";
	
	public static final int LOCATION_SELECTED = 51243;
	
	public static final String LOCATION_LAT = "org.geoscheduler.android.maps.location.lat";

	public static final String LOCATION_LON = "org.geoscheduler.android.maps.location.lon";

	protected LinearLayout tabMain;

	protected LinearLayout tabAdv;

	protected ImageButton btnTabMain;

	protected ImageButton btnTabAdv;

	protected LinearLayout panWhenCnts;

	protected LinearLayout panWhenTimCnts;

	protected LinearLayout panWhenRepCnts;

	protected LinearLayout panWhenRepDays;

	protected LinearLayout panWhenRepEnd;

	protected ImageButton btnSave;

	protected ImageButton btnDelete;

	protected ImageButton btnSelectOnTheMap;

	protected EditText edtEvnTit;

	protected EditText edtEvnDsc;

	protected CheckBox cbEvnPub;

	protected EditText edtTag;

	protected Spinner spnEvnLocations;

	protected Spinner spnEvnRadiusUnits;

	protected CheckBox cbAnyTim;

	protected EditText edtDatFrm;

	protected EditText edtDatTo;

	protected CheckBox cbAllDay;

	protected EditText edtTimFrm;

	protected EditText edtTimTo;

	protected EditText edtEndUntDat;

	protected Spinner spnRepType;

	protected RadioButton rbRepEndNev;

	protected RadioButton rbRepEndUnt;

	protected Event currentEvent;

	protected boolean editMode;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);

		initActivity();		
		initView();

		fillView(currentEvent);		
	}
	
	/**
	 * Fill view with event of the given ID
	 */
	protected void fillView(Event event) {

		edtEvnTit.setText(event.getTitle());
		edtEvnDsc.setText(event.getDescription());
		cbEvnPub.setChecked(event.getEventTypeEnum() == EventType.PUBLIC);
		boolean tmpAnyTime = event.getAlertTypeEnum() != AlertType.LOCATION_OR_TIME
				&& event.getAlertTypeEnum() != AlertType.LOCATION_TIME
				&& event.getAlertTypeEnum() != AlertType.LOCATION_XOR_TIME
				&& event.getAlertTypeEnum() != AlertType.TAG_AND_TIME
				&& event.getAlertTypeEnum() != AlertType.TAG_OR_TIME
				&& event.getAlertTypeEnum() != AlertType.TIME;
		cbAnyTim.setChecked(tmpAnyTime);
		cbAllDay.setChecked(DateTimeHelper.isAllDay(event.getTimeFrom(), event.getTimeTo()));
		if (!cbAnyTim.isChecked()) {
			edtDatFrm.setText(DateTimeHelper.dateFormat.format(event.getTimeFrom()));

			edtDatTo.setText(DateTimeHelper.dateFormat.format(event.getTimeTo()));

			if (!cbAllDay.isChecked()) {
				edtTimFrm.setText(DateTimeHelper.timeFormat.format(event.getTimeFrom()));

				edtTimTo.setText(DateTimeHelper.timeFormat.format(event.getTimeTo()));
			}
		}
		setRepeatTypeSelIndex(event.getRepeatTypeEnum());
		setSelectedRepeatProps(event.getProperties());
		edtTag.setText(FormatHelper.formatTags(event.getTags()));
		
		if (event.getLocation() != null) {
			spnEvnLocations.setSelection(spnEvnLocations.getCount() - 1);
			setRadiusSelection(event.getLocation().getRadius());
		}
	}

	/**
	 * Init common fields of the Activity
	 */
	protected void initActivity() {
		Intent intent = getIntent();
		editMode = intent.hasExtra("org.geoscheduler.android.item.id");

		if (editMode) {
			SQLiteDatabase db = DBHelper.openDB(this);
			long eventId = intent.getLongExtra("org.geoscheduler.android.item.id", -1);

			currentEvent = new Event();
			if (!DBHelper.fetchInst(db, eventId, currentEvent)) {
				/** FIXME [paja]: report error and exit activity */
			} else {
				currentEvent.setTags(DBHelper.fetchTags(db, currentEvent.getId()));
			}
			db.close();
		} else {			
			currentEvent = new Event(null, 0, EventType.PRIVATE, "", "", Calendar.getInstance().getTime(), RepeatType.ONCE, null, null, null,
					AlertType.LOCATION, null, null, "", null);
		}
	}

	/**
	 * Evaluate proper code for selected Repeat type
	 */
	protected RepeatType getSelectedRepeatType() {

		switch (spnRepType.getSelectedItemPosition()) {
		case 0:
			return RepeatType.WEEKLY;
		case 2:
			return RepeatType.DAILY;
		case 3:
			return RepeatType.MONTHLY;
		case 4:
			return RepeatType.YEARLY;
		default:
			return RepeatType.ONCE;
		}
	}

	/** Set closest radius selection for given value  */
	protected void setRadiusSelection(int radius) {		
		
		if (radius < 750) {
			spnEvnRadiusUnits.setSelection(0);
		} else
		if (radius < 1500) {
			spnEvnRadiusUnits.setSelection(1);
		} else
		if (radius < 3500) {
			spnEvnRadiusUnits.setSelection(2);
		} else
		if (radius < 7500) {
			spnEvnRadiusUnits.setSelection(3);
		} else {
			spnEvnRadiusUnits.setSelection(4);
		}
	}
	/**
	 * Set proper Repeat type selection index
	 */
	protected void setRepeatTypeSelIndex(RepeatType rt) {

		if (rt == RepeatType.WEEKLY) {
			spnRepType.setSelection(0);
		} else
		if (rt == RepeatType.DAILY) {
			spnRepType.setSelection(2);
		} else
		if (rt == RepeatType.MONTHLY) {
			spnRepType.setSelection(3);
		} else
		if (rt == RepeatType.YEARLY) {
			spnRepType.setSelection(4);
		} else
		if (rt == RepeatType.ONCE) {
			spnRepType.setSelection(1);
		}
	}

			
	protected String getSelectedRepeatProps() {
		/* FIXME {paja]: code me */
		return null;
	}

	protected void setSelectedRepeatProps(String props) {
		/* FIXME {paja]: code me */		
	}

	/**
	 * Evaluate proper alert type for selected options
	 */
	protected AlertType getSelectedAlertType() {
		if (cbAnyTim.isChecked()) {
			if (spnEvnLocations.getSelectedItemPosition() > 0) {
				return AlertType.LOCATION;
			}
			if (!edtTag.getText().toString().equals("")) {
				return AlertType.TAG;
			}

			/* FIXME [paja]: Exception should be thrown here */
			return AlertType.TAG;
		} else {
			if (spnEvnLocations.getSelectedItemPosition() > 0) {
				return AlertType.LOCATION_TIME;
			}
			if (!edtTag.getText().toString().equals("")) {
				return AlertType.TAG_AND_TIME;
			}
			return AlertType.TIME;
		}
	}

	/**
	 * Save new or existing event
	 */
	protected boolean saveEvent() {
		EventType evnPublic = cbEvnPub.isChecked() ? EventType.PUBLIC : EventType.PRIVATE;
		Date evnFrom = DateTimeHelper.getDateFrom(edtDatFrm.getText().toString(), 
				edtTimFrm.getText().toString(), 
				cbAllDay.isChecked());
		Date evnTo = DateTimeHelper.getDateTo(edtDatTo.getText().toString(), 
				edtTimTo.getText().toString(), 
				cbAllDay.isChecked());
		RepeatType evnRepType = getSelectedRepeatType();		
		String evnProps = getSelectedRepeatProps();
		AlertType evnAlertType = getSelectedAlertType();
		
		/*
		 * TODO: should we save last alert time/location, if the content of the
		 * event is changes?
		 */
		currentEvent.setEventTypeEnum(evnPublic);
		currentEvent.setTitle(edtEvnTit.getText().toString());
		currentEvent.setDescription(edtEvnDsc.getText().toString());
		currentEvent.setRepeatTypeEnum(evnRepType);
		currentEvent.setTimeFrom(evnFrom);
		currentEvent.setTimeTo(evnTo);
		currentEvent.setAlertTypeEnum(evnAlertType);
		currentEvent.setProperties(evnProps);
		currentEvent.incVersion();

		updateLocation();
		updateRadius();	
		updateTags();
		
		long eventId = -1;
		SQLiteDatabase db = DBHelper.openDB(this);
		if ((eventId = DBHelper.storeInst(db, currentEvent)) != -1) {
			DBHelper.updateTags(db, currentEvent.getTags(), eventId);
			db.close();
			return true;
		}
		db.close();
		
		(new AlertDialog.Builder(this)).
			setIcon(R.drawable.stop).
			setTitle(R.string.label_error).
			setMessage(R.string.ee_msg_error_saving).
			setPositiveButton(R.string.label_ok, null).
			create().
			show();
		return false;
	}

	/**
	 * Update tags from text edit control to current event instance 
	 */
	protected void updateTags() {
		String tagText = edtTag.getText().toString();
		String[] tags = tagText.split(",");
	
		if (currentEvent.getTags() == null) {
			currentEvent.setTags(new ArrayList<Tag>());
		} else {
			currentEvent.getTags().clear();
		}		
		
		for (int i = 0; i < tags.length; i++) {

			tags[i] = tags[i].trim();
			SQLiteDatabase db = DBHelper.openDB(this);
			Tag tag = DBHelper.fetchTag(db, tags[i]);
			db.close();
			
			if (tag == null) {
				tag = new Tag(null,tags[i],Locale.getDefault().getCountry());
			}
			
			currentEvent.getTags().add(tag);
		}		
	}
	
	/**
	 * Delete event
	 */
	protected boolean deleteEvent() {
		if (editMode) {
			SQLiteDatabase db = DBHelper.openDB(this);
			boolean out = DBHelper.deleteInst(db, currentEvent);
			db.close();
			
			return out;
		}
		return false;
	}

	/**
	 * Take care of setting up EditEvent layout
	 */
	protected void initView() {
		setContentView(R.layout.editevent);

		tabMain = (LinearLayout) findViewById(R.id.ee_tab_main);
		tabAdv = (LinearLayout) findViewById(R.id.ee_tab_advanced);

		btnTabMain = (ImageButton) findViewById(R.id.ee_tab_main_button);
		btnTabAdv = (ImageButton) findViewById(R.id.ee_tab_advanced_button);

		btnSave = (ImageButton) findViewById(R.id.ee_save_button);
		btnDelete = (ImageButton) findViewById(R.id.ee_delete_button);
		btnSelectOnTheMap = (ImageButton) findViewById(R.id.ee_select_on_map_button);

		if (editMode) {
			btnDelete.setVisibility(VISIBLE);
		} else {
			btnDelete.setVisibility(GONE);
		}

		panWhenCnts = (LinearLayout) findViewById(R.id.ee_whengroup_contents);
		panWhenTimCnts = (LinearLayout) findViewById(R.id.ee_whengroup_time_contents);
		panWhenRepCnts = (LinearLayout) findViewById(R.id.ee_repeatinggroup);
		panWhenRepDays = (LinearLayout) findViewById(R.id.ee_repeating_days);
		panWhenRepEnd = (LinearLayout) findViewById(R.id.ee_repeating_end);

		edtEvnTit = (EditText) findViewById(R.id.ee_event_title);
		edtEvnDsc = (EditText) findViewById(R.id.ee_event_description);
		cbEvnPub = (CheckBox) findViewById(R.id.ee_event_public);
		edtTag = (EditText) findViewById(R.id.ee_tag_text);
		spnEvnLocations = (Spinner) findViewById(R.id.ee_where_location);
		spnEvnRadiusUnits = (Spinner) findViewById(R.id.ee_where_radius);

		cbAnyTim = (CheckBox) findViewById(R.id.ee_when_anytime);
		edtDatFrm = (EditText) findViewById(R.id.ee_when_datefrom);
		edtDatTo = (EditText) findViewById(R.id.ee_when_dateto);
		cbAllDay = (CheckBox) findViewById(R.id.ee_when_allday);
		edtTimFrm = (EditText) findViewById(R.id.ee_when_timefrom);
		edtTimTo = (EditText) findViewById(R.id.ee_when_timeto);
		spnRepType = (Spinner) findViewById(R.id.ee_repeating_type);
		edtEndUntDat = (EditText) findViewById(R.id.ee_repeating_ends_until_date);
		rbRepEndNev = (RadioButton) findViewById(R.id.ee_repeating_ends_never);
		rbRepEndUnt = (RadioButton) findViewById(R.id.ee_repeating_ends_until);

		selectTab(R.id.ee_tab_main);

		setListeners();
		setSpinners();
		fillNew();
	}

	/**
	 * Takes care of showing up tab given by id
	 */
	protected void selectTab(int tabId) {
		setTab(tabMain, btnTabMain, tabId == R.id.ee_tab_main);
		setTab(tabAdv, btnTabAdv, tabId == R.id.ee_tab_advanced);
	}

	/**
	 * Sets state of a single tab
	 * 
	 * @param tab
	 *            Given tab
	 * @param visible
	 *            Given state of the tab
	 */
	protected void setTab(LinearLayout tab, ImageButton tabBtn, boolean visible) {
		if (visible) {
			tab.setVisibility(View.VISIBLE);

			LinearLayout.LayoutParams margins = new LinearLayout.LayoutParams(65, 56);
			margins.setMargins(0, -1, 0, 0);
			tabBtn.setLayoutParams(margins);
			tabBtn.setBackgroundResource(R.drawable.tab_active);
		} else {
			tab.setVisibility(View.GONE);
			LinearLayout.LayoutParams margins = new LinearLayout.LayoutParams(65, 53);
			tabBtn.setLayoutParams(margins);
			tabBtn.setBackgroundResource(R.drawable.tab);
		}
	}

	/**
	 * Takes care of setting up all EditEvent listeners
	 */
	protected void setListeners() {

		final Context ctx = this;

		/* Main tab click listener */
		btnTabMain.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				selectTab(R.id.ee_tab_main);
			}
		});

		/* Advanced tab click listener */
		btnTabAdv.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				selectTab(R.id.ee_tab_advanced);
			}
		});

		/* Save button click listener */
		btnSave.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (saveEvent()) {
					setResult(RESULT_OK);
					finish();
				}
			}
		});

		/* Delete button click listener */
		btnDelete.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (deleteEvent()) {
					setResult(RESULT_OK);
					finish();
				}
			}
		});

		/* Anytime checkbox listener */
		cbAnyTim.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if (!isChecked) {

					/* TODO: Animation */
					panWhenCnts.setVisibility(View.VISIBLE);
					panWhenRepCnts.setVisibility(View.VISIBLE);
					// whenContents.setLayoutParams(new
					// TableLayout.LayoutParams(FILL_PARENT,WRAP_CONTENT));
				} else {
					// int i = whenContents.getHeight();
					// whenContents.setLayoutParams(new
					// TableLayout.LayoutParams(FILL_PARENT,i));

					// Animation verticalHide =
					// AnimationUtils.loadAnimation(ctx,R.anim.vertical_hide);
					// verticalHide.setFillAfter(true);

					// whenContents.startAnimation(verticalHide);
					panWhenCnts.setVisibility(View.GONE);
					panWhenRepCnts.setVisibility(View.GONE);
					// whenContents.setLayoutParams(new
					// LayoutParams(FILL_PARENT,5));
				}
			}
		});

		/* Allday checkbox listener */
		cbAllDay.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if (!isChecked) {
					panWhenTimCnts.setVisibility(VISIBLE);
				} else {
					panWhenTimCnts.setVisibility(GONE);
				}
			}
		});

		/* Date click listener */
		View.OnClickListener dateClick = new View.OnClickListener() {

			@Override
			public void onClick(final View myView) {

				/* Parse date values */
				Date date;
				try {
					date = DateTimeHelper.dateFormat.parse(((EditText) myView).getText().toString());
				} catch (ParseException e) {
					date = Calendar.getInstance().getTime();
				}
				Calendar cal = new GregorianCalendar(DateTimeHelper.dateFormat.getCalendar().getTimeZone());
				cal.setTime(date);

				/* Call date picker */
				new DatePickerDialog(ctx, 
					new DatePickerDialog.OnDateSetListener() {
						@Override
						public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
							/* Set new date value */
							Calendar cal = new GregorianCalendar(DateTimeHelper.dateFormat.getCalendar().getTimeZone());
							cal.set(year, monthOfYear, dayOfMonth);
							((EditText) myView).setText(DateTimeHelper.dateFormat.format(cal.getTime()));
						}
					}, 
					cal.get(Calendar.YEAR), 
					cal.get(Calendar.MONTH), 
					cal.get(Calendar.DAY_OF_MONTH))
				.show();
			}
		};

		edtDatFrm.setOnClickListener(dateClick);
		edtDatTo.setOnClickListener(dateClick);
		edtEndUntDat.setOnClickListener(dateClick);

		/* Time click listener */
		View.OnClickListener timeClick = new View.OnClickListener() {

			@Override
			public void onClick(final View myView) {
				/* Parse date values */
				Date time;
				try {
					time = DateTimeHelper.timeFormat.parse(((EditText) myView).getText().toString());
				} catch (ParseException e) {
					time = Calendar.getInstance().getTime();
				}
				Calendar cal = new GregorianCalendar(DateTimeHelper.timeFormat.getCalendar().getTimeZone());
				cal.setTime(time);

				new TimePickerDialog(ctx, new TimePickerDialog.OnTimeSetListener() {
						@Override
						public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
							/* Set new date value */
							Calendar cal = new GregorianCalendar(DateTimeHelper.timeFormat.getCalendar().getTimeZone());
							cal.set(Calendar.HOUR_OF_DAY, hourOfDay);
							cal.set(Calendar.MINUTE, minute);
							((EditText) myView).setText(DateTimeHelper.timeFormat.format(cal.getTime()));
						}
					}, 
					// FIXME - really comment? getString(R.string.ee_when_time_select), 
					cal.get(Calendar.HOUR_OF_DAY), 
					cal.get(Calendar.MINUTE), 
					true)
				.show();
			}
		};

		edtTimFrm.setOnClickListener(timeClick);
		edtTimTo.setOnClickListener(timeClick);

		/* Repeating type change listener */
		spnRepType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

			@Override
			@SuppressWarnings("unchecked")
			public void onItemSelected(AdapterView parent, View v, int position, long id) {
				switch ((int) id) {
				case 0:
					panWhenRepDays.setVisibility(VISIBLE);
					panWhenRepEnd.setVisibility(VISIBLE);
					break;
				case 1:
					panWhenRepDays.setVisibility(GONE);
					panWhenRepEnd.setVisibility(GONE);
					break;
				case 2:
				case 3:
				case 4:
					panWhenRepDays.setVisibility(GONE);
					panWhenRepEnd.setVisibility(VISIBLE);
					break;
				}
			}

			@Override
			@SuppressWarnings("unchecked")
			public void onNothingSelected(AdapterView arg0) {
				return;
			}
		});

		/*
		 * Radio buttons "Repeating ends" click listener - selecting a button
		 * must be processed manually, cause RadioGroup cannot process
		 * RadioButton in nested LinearLayout
		 */

		CompoundButton.OnCheckedChangeListener radioListener = new CompoundButton.OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				CompoundButton otherBtn;

				if (arg0.getId() == R.id.ee_repeating_ends_never) {
					otherBtn = rbRepEndUnt;
				} else {
					otherBtn = rbRepEndNev;
				}

				otherBtn.setChecked(!arg0.isChecked());

				/* Until-date is visible only if needed */
				if (rbRepEndUnt.isChecked()) {
					edtEndUntDat.setVisibility(VISIBLE);
				} else {
					edtEndUntDat.setVisibility(GONE);
				}

			}
		};

		rbRepEndNev.setOnCheckedChangeListener(radioListener);
		rbRepEndUnt.setOnCheckedChangeListener(radioListener);
		
		/* Location spinners listeners */
		AdapterView.OnItemSelectedListener locationListener = new AdapterView.OnItemSelectedListener() {
			@Override
			@SuppressWarnings("unchecked")
			public void onItemSelected(AdapterView parent, View v, int position, long id) {			

				if (id == parent.getCount() - 1) {
					btnSelectOnTheMap.setVisibility(View.VISIBLE);
				} else {
					btnSelectOnTheMap.setVisibility(View.GONE);
				}
			}
			@Override
			@SuppressWarnings("unchecked")
			public void onNothingSelected(AdapterView arg0) {
				/* Do nothing for the moment */
			}
		};
		
		spnEvnLocations.setOnItemSelectedListener(locationListener);
		
		/* Save button click listener */
		btnSelectOnTheMap.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				selectOnMap();
			}
		});
	}

	/** Select custom location on the map view */
	protected void selectOnMap() {
		boolean hasLocation = currentEvent.getLocation() != null;
		updateLocationPresence();
		
		Intent mapSelect = new Intent();
		mapSelect.setClassName("org.geoscheduler.android", MapOverview.class.getName());
		mapSelect.putExtra(MapOverview.EXTRA_MAP_SELECT_MODE, 1);
		if (hasLocation) {
			mapSelect.putExtra(EditEvent.LOCATION_LAT, currentEvent.getLocation().getLat());
			mapSelect.putExtra(EditEvent.LOCATION_LON, currentEvent.getLocation().getLon());
		}

		startActivityForResult(mapSelect, LOCATION_SELECTED);
    }
	
	/**
	 * Operations for finished subactivity
	 * 
	 * @see android.app.Activity#onActivityResult(int, int, android.content.Intent)
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Bundle extras = data.getExtras();
		
		if (requestCode == LOCATION_SELECTED) {
			
			if (resultCode == RESULT_OK) {
				int tmpLon = 0;
				int tmpLat = 0;
				if (extras.containsKey(LOCATION_LAT)) {
					tmpLat = extras.getInt(LOCATION_LAT);				
					currentEvent.getLocation().setLat(tmpLat);
				}
				if (extras.containsKey(LOCATION_LON)) {
					tmpLon = extras.getInt(LOCATION_LON);
					currentEvent.getLocation().setLon(tmpLon);
				}				
				Toast.makeText(EditEvent.this, 
						getString(R.string.ee_msg_location_set, tmpLon, tmpLat), 
						Toast.LENGTH_SHORT).show();
			}
		}
	}
	
	/** Select current location as the event location */
	protected void selectHere() {
		LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		boolean wasok = false;
		if (lm != null) {
			android.location.Location loc = lm.getLastKnownLocation(FIXED_LOCATION_PROVIDER);
			
			if (loc != null) {
				wasok = true;
				Double lat = loc.getLatitude() * 1E6;
				Double lon = loc.getLongitude() * 1E6;
				
				currentEvent.getLocation().setLat(lat.intValue());
				currentEvent.getLocation().setLon(lon.intValue());
			}
		}
		
		if (!wasok) {
			Toast.makeText(this.getApplicationContext(), R.string.ee_msg_location_null, 10000);
		}
	}
	
	/** Update presence of location on current event */
	protected void updateLocationPresence() {
		if (spnEvnLocations.getSelectedItemPosition() == 0) {
			currentEvent.setLocation(null);
		} else {
			if (currentEvent.getLocation() == null) {
				Location tmpLoc = new Location(null, 0, null, null, null, null);
				currentEvent.setLocation(tmpLoc);
				selectHere();
			}
		}
	}
	
	protected void updateLocation() {

		long id = spnEvnLocations.getSelectedItemId();
		
		updateLocationPresence();
		
		if (id == 0) {
			/* Clean up location "Anywhere" */			
		} else
		if (id == 1) {
			/* Select current location for "Here*/
			selectHere();
		} else
		if (id == spnEvnLocations.getCount() - 1) {
			/* If was not selected, here is chosen */			
		} else				
		if (id != 0) {
			/* Choose preset location */
			/* TODO [paja]: code me! */
		}
	}
	
	/** Update current radius value if location is selected */
	protected void updateRadius() {
		updateLocationPresence();
		
		if (currentEvent.getLocation() != null) {
			/* Radius list is fixed yet */
			switch (spnEvnRadiusUnits.getSelectedItemPosition()) {
			case 0:
				currentEvent.getLocation().setRadius(500);
				break;
			case 1:
				currentEvent.getLocation().setRadius(1000);
				break;
			case 2:
				currentEvent.getLocation().setRadius(2000);
				break;
			case 3:
				currentEvent.getLocation().setRadius(5000);
				break;
			case 4:
				currentEvent.getLocation().setRadius(10000);
				break;
			}
		}
	}
	
	/** Fill the content for new item */
	protected void fillNew() {
		edtEvnTit.setText("");

		edtEvnDsc.setText("");

		edtTag.setText("");

		cbAnyTim.setChecked(true);

		/* Setup default time period to comming hour */
		Calendar tmpCal = Calendar.getInstance();
		tmpCal.setTimeInMillis(tmpCal.getTimeInMillis() + 3600000);
		tmpCal.set(Calendar.MINUTE, 0);
		tmpCal.set(Calendar.SECOND, 0);
		tmpCal.set(Calendar.MILLISECOND, 0);
		Date tmpFrom = tmpCal.getTime();
		/* Current time plus one hour */
		Date tmpTo = new Date(tmpCal.getTimeInMillis() + 3600000);

		edtDatFrm.setText(DateTimeHelper.dateFormat.format(tmpFrom));

		edtDatTo.setText(DateTimeHelper.dateFormat.format(tmpTo));

		cbAllDay.setChecked(true);

		edtTimFrm.setText(DateTimeHelper.timeFormat.format(tmpFrom));

		edtTimTo.setText(DateTimeHelper.timeFormat.format(tmpTo));

		edtEndUntDat.setText(DateTimeHelper.dateFormat.format(Calendar.getInstance().getTime()));

		spnRepType.setSelection(1);

		rbRepEndNev.setChecked(true);

		spnEvnLocations.setSelection(0);
		
		spnEvnRadiusUnits.setSelection(0);
	}

	/**
	 * Fills all spinners
	 */
	protected void setSpinners() {
		
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.ee_where_location, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spnEvnLocations.setAdapter(adapter);

		adapter = ArrayAdapter.createFromResource(this, R.array.ee_where_radius, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spnEvnRadiusUnits.setAdapter(adapter);

	}
}
